<?php
require_once 'config21.php';
// 验证登录状态
if (!isset($_SESSION['userid'])) {
    header("Location: login21.php");
    exit;
}

// 获取记录id并验证
$no = isset($_GET['id']) ? intval($_GET['id']) : 0;
if ($no <= 0) {
    die('无效的记录ID');
}

// 错误消息数组
$errors = [];
$success = false;

// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['edit_nationalbird'])) {
    // 获取并过滤输入
    $ccountry = trim($_POST['ccountry']);
    $country = trim($_POST['country']);
    $cname = trim($_POST['cname']);
    $name = trim($_POST['name']);

    // 验证必填字段
    if (empty($ccountry)) $errors[] = '国籍不能为空';
    if (empty($country)) $errors[] = '国籍(EN)不能为空';
    if (empty($cname)) $errors[] = '鸟名不能为空';
    if (empty($name)) $errors[] = '鸟名(EN)不能为空';

    // 处理图片上传
    $updatePicture = false;
    if (!empty($_FILES['picture']['name'])) {
        $picture = $_FILES['picture']['name'];
        $filetype = strtolower(substr($picture, strrpos($picture, '.')));

        // 验证文件类型
        $allowedTypes = ['.jpg', '.jpeg', '.png', '.gif'];
        if (!in_array($filetype, $allowedTypes)) {
            $errors[] = '文件类型必须是JPG、PNG或GIF';
        }

        if (empty($errors)) {
            $updatePicture = true;
            $savedir = "images/" . unipid() . $filetype;    // 使用唯一文件名

            // 移动上传的文件
            if (!move_uploaded_file($_FILES['picture']['tmp_name'], $savedir)) {
                $errors[] = '文件上传失败，请检查目录权限';
            }
        }
    }

    // 如果没有错误，执行数据库更新
    if (empty($errors)) {
        try {
            // 准备SQL语句
            if ($updatePicture) {
                $sql = "UPDATE nationalbird
                SET ccountry=?, country=?, cname=?, name=?, picture=?
                WHERE no=?";
                $stmt = $conn->prepare($sql);
                $stmt->bind_param('sssssi', $ccountry, $country, $cname, $name, $savedir, $no);
            } else {
                $sql = "UPDATE nationalbird
                SET ccountry=?, country=?, cname=?, name=?
                WHERE no=?";
                $stmt = $conn->prepare($sql);
                $stmt->bind_param('ssssi', $ccountry, $country, $cname, $name, $no);
            }

            // 执行更新
            if ($stmt->execute()) {
                $success = true;
                $_SESSION['success_message'] = "国鸟记录修改成功";
                header("Location: list_nationalbird21.php");
                exit;
            } else {
                $errors[] = '数据库更新失败:' . $stmt->error;
            }

            $stmt->close();
        } catch (Exception $e) {
            $errors[] = '发生错误:' . $e->getMessage();
        }
    }
} else {
    // 获取现有记录数据
    $sql = "SELECT * FROM nationalbird WHERE no=?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('i', $no);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows == 0) {
        die('未找到该记录!');
    }

    $info = $result->fetch_assoc();
    $stmt->close();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>修改国鸟记录</title>
    <link rel="stylesheet" href="style21.css">
    <style>
        .error-message {
            color: red;
            margin-bottom: 10px;
        }
    </style>
</head>
<body>
    <!-- 显示错误信息 -->
    <?php if (!empty($errors)) : ?>
        <div class="error-message">
            <ul>
                <?php foreach ($errors as $error) : ?>
                    <li><?php echo $error; ?></li>
                <?php endforeach; ?>
            </ul>
        </div>
    <?php endif; ?>
    <form method="post" enctype="multipart/form-data" name="form1" id="form1">
        <table width="400" border="1">
            <tbody>
                <tr>
                    <td colspan="2" align="center">修改记录</td>
                </tr>
                <tr>
                    <td>国籍</td>
                    <td><input type="text" name="ccountry" id="ccountry" value="<?php echo htmlspecialchars($info['ccountry']); ?>" required></td>
                </tr>
                <tr>
                    <td>国籍(英文)</td>
                    <td><input type="text" name="country" id="country" value="<?php echo htmlspecialchars($info['country']); ?>" required></td>
                </tr>
                <tr>
                    <td>鸟名</td>
                    <td><input type="text" name="cname" id="cname" value="<?php echo htmlspecialchars($info['cname']); ?>" required></td>
                </tr>
                <tr>
                    <td>鸟名(英文)</td>
                    <td><input type="text" name="name" id="name" value="<?php echo htmlspecialchars($info['name']); ?>" required></td>
                </tr>
                <tr>
                    <td>图片</td>
                    <td>
                        <input type="file" name="picture" id="picture">
                        <?php if (!empty($info['picture'])) : ?>
                            <img src="<?php echo htmlspecialchars($info['picture']); ?>" width="50px" height="36px" alt="当前照片">
                        <?php endif; ?>
                    </td>
                </tr>
                <tr>
                    <td colspan="2" align="center">
                        <input type="submit" name="edit_nationalbird" id="submit" value="修改">
                        &nbsp;&nbsp;&nbsp;
                        <input type="reset" name="reset" id="reset" value="重置">
                    </td>
                </tr>
            </tbody>
        </table>
        <p>&nbsp;</p>
    </form>
</body>
</html>